package com.imay.live.proto.helper;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by jeaman on 2017/4/12.
 */

public class ProtoRequestHelper {
    private static Set<ProtoRequest> mRequestList = new HashSet<>();

    public static ProtoRequest task(ProtoRequestParams params) {
        ProtoRequest request = new ProtoRequest(params.getType());
        request.setCommand(params.getCommand());
        request.setData(params.getData());
        addRequest(request);    //加到队列
        return request;
    }

    public static void addRequest(ProtoRequest request) {
        synchronized (mRequestList) {
            mRequestList.add(request);
        }
    }

    public static void removeRequest(ProtoRequest request) {
        synchronized (mRequestList) {
            mRequestList.remove(request);
        }
    }

    public static void cancelRequest(int tag) {
        synchronized (mRequestList) {
            Iterator<ProtoRequest> iterator = mRequestList.iterator();
            while (iterator.hasNext()) {
                ProtoRequest request = iterator.next();
                //使用hashCode作为tag
                if (request.getTag() == tag) {
                    request.destroy();
                    iterator.remove();
                }
            }
        }
    }

    public static void cancelAllRequest() {
        synchronized (mRequestList) {
            Iterator<ProtoRequest> iterator = mRequestList.iterator();
            while (iterator.hasNext()) {
                ProtoRequest request = iterator.next();
                request.destroy();
                iterator.remove();
            }
        }
    }
}
